#include "EditorSideBarViewModel.h"
#include "EditorSideBarModel.h"

#include "Ability/EditorAbilityModel.h"
#include "Ability/EditorAbilityViewModel.h"

#include "Framework/Editor.h"

void REditorSideBarViewModel::BindModel(TSharedObjectPtr<REditorSideBarModel> InModel)
{   
    Model=InModel;

    Abilitys.Reserve(Model->GetAbilitysNum());
    for(int64_t i = 0; i < Model->GetAbilitysNum() ; i++)
    {
        auto AbilityModel = Model->GetAbility(i);
        
        auto ViewModelClass = REditor::Get()->GetViewModelClass(AbilityModel->GetClass());
        auto AbilityViewModel = NewObject<REditorAbilityViewModel>(ViewModelClass, this);
        AbilityViewModel->BindModel(AbilityModel);
        Abilitys.Add(AbilityViewModel);
    }

    Model->OnAbilityAdded.Bind([this](int64_t Index, TSharedObjectPtr<REditorAbilityModel> InAbility)
    {
        auto ViewModelClass = REditor::Get()->GetViewModelClass(InAbility->GetClass());
        auto AbilityViewModel = NewObject<REditorAbilityViewModel>(ViewModelClass, this);
        AbilityViewModel->BindModel(InAbility);
        Abilitys.Insert(Index, AbilityViewModel);
        OnAbilityAdded.ExecuteIfBound(Index,AbilityViewModel);
    });

    Model->OnAbilityRemoved.Bind([this](int64_t Index)
    {
        Abilitys.RemoveAt(Index);
        OnAbilityRemoved.ExecuteIfBound(Index);
    });
}


void REditorSideBarViewModel::OnAbilityClicked(int64_t InIndex)
{
    if(Model->ActivedAbilityIndex == InIndex)
    {
        Model->ActivedAbilityIndex = -1;
    }
    else
    {
        Model->ActivedAbilityIndex = InIndex;
    }
}

bool REditorSideBarViewModel::IsAbilityHighlight(int64_t InIndex) const
{
    return Model->ActivedAbilityIndex == InIndex;
}

bool REditorSideBarViewModel::IsAbilityVisible(int64_t InIndex) const
{
    return Model->ActivedAbilityIndex==InIndex;
}

int64_t REditorSideBarViewModel::GetAbilitysNum() const
{
    return Abilitys.Num();
}

TSharedObjectPtr<RTexture2D> REditorSideBarViewModel::GetAbilityIcon(int64_t InIndex) const
{
    if(Model->ActivedAbilityIndex==InIndex
        || HoveredAbilityIndex==InIndex
    )
    {
        return Abilitys[InIndex]->GetHighlightIcon();
    }
    return Abilitys[InIndex]->GetIcon();
}

CString REditorSideBarViewModel::GetAbilityTitle(int64_t InIndex) const
{
    return Abilitys[InIndex]->GetName();
}

TSharedObjectPtr<REditorAbilityViewModel> REditorSideBarViewModel::GetAbility(int64_t InIndex) const
{
    return Abilitys[InIndex];
}

EEditorAbilityActiveBarPositionType REditorSideBarViewModel::GetActiveBarPosition() const
{
    return Model->ActiveBarPositionType;
}
